<script setup lang="ts">
import Carousel from '../components/Carousel.vue';
import Cates from '../components/Cates.vue';
import { userinfo } from '@/stores/counter';
import SubNewsList from '../components/SubNewsList.vue';
import { ref, inject, onMounted, onBeforeMount } from 'vue';
import type { Cate } from '../types/types.d.ts';
import getSubArticleList from '@/api/getSubArticleList';
import { useRoute, useRouter } from 'vue-router';
import subscribeCate from '@/api/subscribeCate';
const { getSubscribeStatus, setSubscribeStatus, getSubscribeList } =
  subscribeCate();
const cates = inject('cates') as Cate[];
const { subList } = getSubArticleList();
const route = useRoute();
const router = useRouter();
const user = userinfo();
const loading = ref(false);

let isSubcribe = ref(false);
// const cate = ref(parseInt(route.params.cate as string))
// 寻找 cates 中的 cate.id 与 route.params.cate 相同的 cate
const cateData = cates.find(
  (cate) => cate.id === parseInt(route.params.cate as string)
);

onBeforeMount(async () => {
  if (user.pages.sub.cate == -1 || user.pages.sub.cate != cateData!.id) {
    loading.value = true;
    user.pages.sub.list = [];
    user.pages.sub.total = 0;
    await subList(cateData!.id);
  }
  loading.value = false;
  isSubcribe.value = await getSubscribeStatus();
});

function goback() {
  router.go(-1);
}

async function setSubscribeStatusFront() {
  isSubcribe.value = !isSubcribe.value;
  if (!(await setSubscribeStatus(isSubcribe.value))) {
    isSubcribe.value = !isSubcribe.value;
  }
}
</script>

<template>
  <div class="sub-div">
    <div class="goback" @click="goback()">
      <el-icon color="#f5900a">
        <ArrowLeftBold />
      </el-icon>
    </div>
    <div class="sub-title font-xbs">{{ cateData!.name }}</div>
    <div class="subscribe-cate">
      <el-icon
        color="#f5900a"
        @click="setSubscribeStatusFront()"
        v-if="isSubcribe"
      >
        <Check />
      </el-icon>
      <el-icon color="#f5900a" @click="setSubscribeStatusFront()" v-else>
        <Bell />
      </el-icon>
    </div>
    <div class="sub-newp" v-loading="loading">
      <SubNewsList />
    </div>
  </div>
</template>

<style scoped>
.sub-div {
  width: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.sub-title {
  font-size: 40px;
  font-weight: bold;
}

.sub-newp {
  display: flex;
  width: 100%;
  min-height: 500px;
}

.goback {
  width: 40px;
  height: 40px;
  background-color: white;
  box-shadow: #475669 1px 1px;
  border-radius: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  align-self: flex-start;
  margin-left: 100px;
  cursor: pointer;
}

.subscribe-cate {
  width: 40px;
  height: 40px;
  background-color: white;
  box-shadow: #475669 1px 1px;
  border-radius: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  align-self: flex-start;
  margin-left: 100px;
  cursor: pointer;
}
</style>
